//
//  MYPublishEditAssociatedGoodsVC.m
//  MuYing
//
//  Created by tbb on 2019/8/15.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYPublishEditAssociatedGoodsVC.h"
#import "YQSearchBaseBar.h"
#import "MYShopSearchScreenView.h"
#import "MYPublishEditProductModel.h"
#define KTAG_SELECTBTN_BASE 10100
@interface MYPublishEditAssociatedGoodsVC ()<YQSearchBaseBarDelegate,MYShopCarCellDelegate>
@property (nonatomic, strong) YQSearchBaseBar * searchBar;

@property (nonatomic, copy) NSString * keyword;
@end

@implementation MYPublishEditAssociatedGoodsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kYQLS(@"选择相关商品");
    self.rightItemTitle = kYQLS(@"确定");
    [self.rightItem setTitleColor:kAPPThemeColor forState:(UIControlStateNormal)];
}

-(void)rightItemAction:(UIButton *)sender {
    if (self.selectParentGoodsBlock) {
        NSMutableArray *selectArr = @[].mutableCopy;
        
        for (MYPublishEditProductModel *productModel in self.dataArr) {
            for (MYPublishEditProductGoodsModel *goodsModel in productModel.invitationProductVo) {
                if (goodsModel.isSelect) {
                    //判断选择的是那个订单
                    goodsModel.orderSn = productModel.orderSn;
                    [selectArr addObject:goodsModel];
                }
            }
        }
        
        
        self.selectParentGoodsBlock(selectArr.copy);
    }
    [self.navigationController popViewControllerAnimated:true];
}

-(void)setupView {
    [super setupView];
    UIView *searchBgView = [UIView new];
    searchBgView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:searchBgView];
    [searchBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    [searchBgView addSubview:self.searchBar];

    UIButton *screenBtn = [UIButton buttonWithType:0];
    screenBtn.hidden = YES;
    [screenBtn setImage:YQIMG(@"shop_screen_icon") forState:(UIControlStateNormal)];
    [searchBgView addSubview:screenBtn];
    [screenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.searchBar.mas_centerY).mas_equalTo(0);
        make.right.mas_equalTo(-12);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    #pragma mark - 侧拉屏幕
    [screenBtn addTapAction:^(id  _Nonnull sender) {
        
    }];
    
    self.listTableView.frame = CGRectMake(0, 44, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-44);
    kYQREGISTERTABLEVIEWCNIBHeaderFooter(@"MYPublishEditAssociatedGoodsHeader")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYShopCarCell")
    [self getProductListSearch:NO];
}
//GET
-(void)getProductListSearch:(BOOL)search {
    
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"parentName"] = self.parentName;
    NSString *url = kGET_INVITATION_PRODUCT_GOODS_URL;
    if (search) {
        parameters[@"keyword"] = self.keyword;
        url = kGET_INVITATION_SEARCH_ORDER_URL;
    }

    
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendGetRequest:url  parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            for (MYPublishEditProductModel *orderModel in self.dataArr) {
                for (MYPublishEditProductGoodsModel *goodsModel in orderModel.invitationProductVo) {
                    if (goodsModel.select) {
                        [self.selectedArr addObject:goodsModel];
                    }
                    
                }
            }
            [self.dataArr removeAllObjects];
            NSArray *arr = [NSArray modelArrayWithClass:MYPublishEditProductModel.class json:responseObject.data];
            
            [self.dataArr addObjectsFromArray:arr];
            
            for (MYPublishEditProductModel *orderModel in self.dataArr) {
                for (MYPublishEditProductGoodsModel *goodsModel in orderModel.invitationProductVo) {
                    for (MYPublishEditProductGoodsModel *selectGoodsModel in self.selectedArr) {
                        if ([selectGoodsModel.productId isEqualToString:goodsModel.productId] && [orderModel.orderSn isEqualToString:selectGoodsModel.orderSn]) {
                            goodsModel.select = YES;
                        }
                    }
                }
            }
            
            for (MYPublishEditProductModel *orderModel in self.dataArr) {
                for (MYPublishEditProductGoodsModel *goodsModel in orderModel.invitationProductVo) {
                    orderModel.select = YES;
                    if (!goodsModel.isSelect) {
                        //存在一个未选当前section就不是全选
                        orderModel.select = NO;
                        break;
                    }
                }
            }
            
            [self.selectedArr removeAllObjects];
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error)
    }];
    
}

#pragma mark -- MYShopCarCellDelegate
-(void)didSelectGoodAction:(NSIndexPath *)indexPath {
    MYPublishEditProductModel *orderModel = nil;
    if (self.dataArr.count > indexPath.section) {
        orderModel = self.dataArr[indexPath.section];
    }
    
    MYPublishEditProductGoodsModel *productModel = nil;
    if (indexPath.row < orderModel.invitationProductVo.count) {
        productModel = orderModel.invitationProductVo[indexPath.row];
    }
    
    productModel.select = !productModel.isSelect;
    for (MYPublishEditProductGoodsModel *productModel in orderModel.invitationProductVo) {
        orderModel.select = YES;
        if (!productModel.isSelect) {
            //存在一个未选当前section就不是全选
            orderModel.select = NO;
            break;
        }
    }
    [self.listTableView reloadData];
    
}
#pragma mark -- MYShopCarCellDelegate end

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MYPublishEditProductModel *productModel = nil;
    if (section < self.dataArr.count) {
        productModel = self.dataArr[section];
    }
    return productModel.invitationProductVo.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MYPublishEditProductModel *orderModel = nil;
    if (self.dataArr.count > indexPath.section) {
        orderModel = self.dataArr[indexPath.section];
    }
    
    MYPublishEditProductGoodsModel *productModel = nil;
    if (indexPath.row < orderModel.invitationProductVo.count) {
        productModel = orderModel.invitationProductVo[indexPath.row];
    }
    
    MYShopCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopCarCell"];
    cell.isCarCell = NO;
    cell.countLb.hidden = YES;
    cell.titleLb.text = productModel.productName;
    [cell.goodsIcon setImageURL:[NSURL URLWithString:productModel.defaultImage]];
    cell.specificationLb.text = productModel.specification;
    cell.priceLb.text = [NSString stringWithFormat:@"￥%@",productModel.price];
    cell.selectBtn.selected = productModel.isSelect;
    cell.indexPath = indexPath;
    cell.delegate = self;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 124;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MYPublishEditProductModel *productModel = nil;
    if (self.dataArr.count > section) {
        productModel = self.dataArr[section];
    }
    MYPublishEditAssociatedGoodsHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYPublishEditAssociatedGoodsHeader"];
    header.orderNsLb.text = [NSString stringWithFormat:@"%@: %@",kYQLS(@"订单编号"),productModel.orderSn];
    header.orederDateLb.text = [NSString stringWithFormat:@"%@: %@",kYQLS(@"下单时间"),productModel.createTimeStr];
    header.selectBtn.tag = KTAG_SELECTBTN_BASE + section;
    [header.selectBtn addTarget:self action:@selector(selectProductGoods:) forControlEvents:(UIControlEventTouchUpInside)];
    header.selectBtn.selected = productModel.isSelect;
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 54;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
-(void)selectProductGoods:(UIButton *)sender {
    NSInteger section = sender.tag - KTAG_SELECTBTN_BASE;
    MYPublishEditProductModel *productModel = nil;
    if (self.dataArr.count > section) {
        productModel = self.dataArr[section];
    }
    
    productModel.select = !productModel.isSelect;
    
    for (MYPublishEditProductGoodsModel *goodsModel in productModel.invitationProductVo) {
        goodsModel.select = productModel.isSelect;
    }
    
    [self.listTableView reloadData];
    
}
#pragma makr -- YQSearchBaseBarDelegate
- (void)yq_searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.keyword = searchBar.text;
    if ([self.keyword removeStringSpace].length > 0) {
        [self getProductListSearch:YES];
    }else{
        [self getProductListSearch:NO];
    }
    
}
-(void)yq_textFieldShouldClear:(UITextField *)textField {
    [self getProductListSearch:NO];
}
-(void)yq_shouldChangeText:(NSString *)text {
    if ([text removeStringSpace].length == 0) {
        [self getProductListSearch:NO];
    }else{
        self.keyword = text;
        [self getProductListSearch:YES];
    }
}
#pragma makr -- YQSearchBaseBarDelegate end

#pragma makr -- lazy
-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(12, 0, SCREEN_WIDTH - 68, 28)];
        _searchBar.top = 2;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"查找你要的商品");
    }
    return _searchBar;
}

-(NSMutableArray *)selectedArr {
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}

#pragma makr -- lazy end
@end
